package mspbots.data.tl.prod.hubspot.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.hubspot.mapper.HubspotTicketMapper;
import mspbots.data.tl.prod.hubspot.model.HubspotTicket;
import mspbots.data.tl.prod.hubspot.service.HubspotTicketService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Jay.Yang
 */

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class HubspotTicketServiceImpl extends AbstractBaseServiceImpl<HubspotTicketMapper, HubspotTicket>
        implements HubspotTicketService {

    @Override
    public void sync(ResultEntity content) {
        JsonNode entity = content.getEntity();
        JsonNode properties = entity.get("properties");
        HubspotTicket data = HubspotTicket.builder()
                .ticketId(content.getId())
                .archived(ObjectUtils.isEmpty(entity.get("archived")) ? false : entity.get("archived").asBoolean())
                .createdAt(ObjectUtils.isEmpty(entity.get("createdAt")) ? null :
                        LocalDateTime.parse(content.getEntity().get("createdAt").asText(), DateTimeFormatter.ISO_DATE_TIME))
                .updatedAt(ObjectUtils.isEmpty(entity.get("updatedAt")) ? null :
                        LocalDateTime.parse(content.getEntity().get("updatedAt").asText(), DateTimeFormatter.ISO_DATE_TIME))
                .subject(ObjectUtils.isEmpty(properties.get("subject")) ? null : properties.get("subject").asText())
                .content(ObjectUtils.isEmpty(properties.get("content")) ? null : properties.get("content").asText())
                .sourceType(ObjectUtils.isEmpty(properties.get("source_type")) ? null : properties.get("source_type").asText())
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());

        HubspotTicket dbData = super.baseMapper.selectOne(Wrappers.<HubspotTicket>lambdaQuery()
                .eq(HubspotTicket::getTenantCode, data.getTenantCode())
                .eq(HubspotTicket::getTicketId, data.getTicketId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }
}
